﻿using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.BusinessData.SharedService;
using Microsoft.SharePoint.BusinessData.Administration;
using Microsoft.SharePoint.BusinessData.Parser;

namespace Office365.Helper.BCSModeler
{
    public class Bdcm
    {
        #region Privates
        private string _siteUrl;
        private string _filePath;
        #endregion

        #region cstors
        private Bdcm()
        {
        }

        public Bdcm(string siteUrl, string filePath)
        {
            _siteUrl = siteUrl;
            _filePath = filePath;
        }
        #endregion

        #region Public Methods
        public void Import()
        {
            string[] nonCriticalErrors;

            // Get the model data from the .bdcm file
            string modelData = System.IO.File.ReadAllText(_filePath);

            using (SPSite site = new SPSite(_siteUrl))
            {
                using (new SPServiceContextScope(SPServiceContext.GetContext(site)))
                {
                    // Get the BDC Service
                    //BdcService service = SPFarm.Local.Services.GetValue<BdcService>(string.Empty);
                    BdcService service = SPFarm.Open(@"Data Source=WINSRV\SharePoint;Initial Catalog=SharePoint_Config_4c55beea-0427-42ac-99a1-49c9b275fb94;Integrated Security=True;Enlist=False;Connect Timeout=15").Services.GetValue<BdcService>(String.Empty);

                    // Get the catalog of the referenced BDC service.
                    AdministrationMetadataCatalog catalog = service.GetAdministrationMetadataCatalog(SPServiceContext.Current);

                    // Import the XML definition.
                    catalog.ImportPackage(modelData, out nonCriticalErrors, PackageContents.All, string.Empty, false, Guid.NewGuid());
                }
            }
        }
        #endregion
    }
}
